<%- include("header",{type:'signin'}) %>
	<div class="container">
		<form class="form create" method="post ">
			<div>
				<label>开始页码：</label>
				<input placeholder="请填写数字" type="number" name="pageS">
			</div>
			<div>
				<label>结束页码：</label>
				<input placeholder="请填写数字" type="number" name="pageE">
			</div>
			<div>
				<label>搜索关键词：</label>
				<input placeholder="填写文字" type="text" name="keyword">
			</div>
			<div class="submit">爬取</div>
		</form>
	</div>

	<div id="userMsg" style="position: absolute;	margin-top: 100px; margin-left:3%"></div>

	<script type="text/javascript">

		let sign = false;

		$(window).keyup(function (e) {
			//console.log(e.keyCode)
			if (e.keyCode == 13) {
				$('.submit').click()
			}
		})

		/* 封装 WebSocket 实例化的方法  */
		var CreateWebSocket = (function () {
			return function (urlValue) {
				if (window.WebSocket) return new WebSocket(urlValue);
				if (window.MozWebSocket) return new MozWebSocket(urlValue);
				return false;
			}
		})();
		/* 实例化 WebSocket 连接对象, 地址为 ws 协议 */
		var webSocket = CreateWebSocket("ws://127.0.0.1:3001/websocket");
		/* 接收到服务端的消息时 */
		webSocket.onmessage = function (msg) {
			if (msg.data != "end") {
				$("#userMsg").prepend(`<p>${msg.data}</p>`);
			} else {
				$("#userMsg").prepend(`<b>本次爬取结束</b>`);
			}
			console.log(msg);
		};
		/* 关闭时 */
		webSocket.onclose = function () {
			$("#userMsg").prepend(`<b>本次爬取结束</b>`);
			console.log("关闭连接");
		};

		/* 发送消息 */
		$('.submit').click(() => {
			if ($('input[name=pageE]').val().trim() == '' || $('input[name=pageS]').val().trim() == '' || $('input[name=keyword]').val().trim() == '') {
				alert('参数丢失')
			} else {
				if (sign == true) {
					return;
				}
				$(this).attr('disabled', "true");
				$('.submit').addClass("submit-unenable");
				$('.submit-unenable').css({'cursor':'wait'});
				sign = true;
				let data = $('.form').serialize();
				webSocket.send(data);
				$("#userMsg").prepend(`<b>正在初始化请求。。。</b>`);
				$("#userMsg").prepend(`<p>请求参数 ${data}</p>`);
			}
		})
	</script>
	<% include footer %>